package com.yz.xyt.componet;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yz.xyt.domain.Major;
import com.yz.xyt.domain.vo.MajorImportVo;
import com.yz.xyt.service.IMajorService;
import com.yz.xyt.service.impl.MajorServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * major监听器(EasyExcel导入)
 * @author JW.WANG
 */
@Component
public class MajorListener extends AnalysisEventListener<MajorImportVo> {

    private static final Logger LOGGER = LoggerFactory.getLogger(MajorListener.class);


    private static final Integer COUNT = 50;

    private Set<MajorImportVo> majorSet = new HashSet<>();

    @Autowired
    private IMajorService majorService;

    @Override
    public void invoke(MajorImportVo major, AnalysisContext analysisContext) {
        LOGGER.info("解析了一条记录，" + major.toString());
        majorSet.add(major);

        if(majorSet.size() == COUNT){
            List<Major> majorList = majorService.convertMajor(majorSet);
            if (!majorList.isEmpty()){
                majorService.syncAddMajor(majorList);
            }
            majorSet.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<Major> majorList = majorService.convertMajor(majorSet);
        if (!majorList.isEmpty()){
            majorService.syncAddMajor(majorList);
        }
        majorService.syncAddMajor(majorList);
        LOGGER.info("专业数据导入完成");
        majorSet.clear();
    }
}
